<?php

namespace app\common\Notices;

require_once __DIR__ . "/../Notices/LogHandler.php";
use Common\Components\Joinpay;
use Common\Services\OrderPayService;


/**
* 汇聚支付异步通知处理方法
**/

class JoinpayNotice{
    /**
     * 验证异步回调参数
     * @param {"r1_MerchantNo":"888107000000259","r2_OrderNo":"MG79202004282000472015058","r3_Amount":"0.01","r4_Cur":"1","r5_Mp":"","r6_Status":"100","r7_TrxNo":"100220042880722619","r8_BankOrderNo":"100220042880722619","r9_BankTrxNo":"4200000533202004287492354177","ra_PayTime":"2020-04-28+20%3A02%3A04","rb_DealTime":"2020-04-28+20%3A02%3A04","rc_BankCode":"WEIXIN_GZH","hmac":"6dd803231eb37220c560246699379b6c","out_trade_no":"MG79202004282000472015058"}
     */
    private function NotifyProcess()
    {
        $params = $_GET;//get参数
        if (!empty($params['r6_Status']) && $params['r6_Status'] == '100') {
                $params['out_trade_no'] = $params['r2_OrderNo'];
                 LogHandler::DEBUG("服务器通知参数:" . json_encode($params,320));
                // TODO 进行签名验证
                $isCheckSign = Joinpay::checkSign($params);
                if(!$isCheckSign){
                    LogHandler::DEBUG("签名错误...");
                    return false;
                }
                //处理平台订单支付状态同步
                $orderService = new OrderPayService();
                $transaction_id = empty($params['r9_BankTrxNo']) ? '2020' : $params['r9_BankTrxNo'];
                $pay_time = strtotime(urldecode(urldecode($params['ra_PayTime'])));
                $params['pay_out_trade_no'] = $params['r7_TrxNo'];
                $params['online_pay_type'] = 2;
                if(!$orderService->sysTransactionNotify($params,$params["r3_Amount"],$transaction_id,$pay_time)) {
                    LogHandler::DEBUG($orderService->err_message);//获取订单状态更新失败原因
                    return false;
                }
                echo "success";    //请不要修改或删除
                LogHandler::DEBUG("通知返回结果:success");
        }else{
            // TODO 验签失败则记录异常日志，并在response中返回failure.
            //验证失败
            echo "failure";
        }
    }
    /**
     *
     * 初始化异步通知
     *
     **/
    public function sendProcess()
    {
        //初始化日志
        $logHandler= new CLogFileHandler(__DIR__ . "/../Notices/noticeLog/joinpay/joinpay_" .date('Y-m-d').'.log');
        $log = LogHandler::Init($logHandler, 15);
        //LogHandler::DEBUG("sendProcess begin notify");
        self::NotifyProcess();
    }

}

